<template>
  <n-scrollbar x-scrollable style="max-height: 100vh">
    <CommonPage>
        <div>
            <n-form ref="form"
                    :model="searchCondition"
                    :show-require-mark="false"
                    label-align="right"
                    label-placement="left"
                    label-width="80px">
                <div>
                    <div class="grid md:flex md:flex-wrap md:gap-x-1">
              <n-form-item>
                <label style="width: 100px">产品名称:</label>
                  <n-input
                          v-model:value="searchCondition.name"
                          placeholder="输入产品名称">
                  </n-input>
              </n-form-item>
              <n-form-item>
                  <label style="width: 70px;margin-left: 10px">产品分类：</label>
                  <n-cascader
                          v-model:value="searchCondition.categoryId"
                          style="width:160px"
                          :options="option"
                          filterable
                  >
                  </n-cascader>
              </n-form-item>
              <n-form-item>
                  <label style="margin-left: 10px">产品品牌：</label>
                 <n-select v-model:value="searchCondition.brandName"
                           :options="brands"
                           style="width: 200px"
                 ></n-select>
              </n-form-item>
              <n-form-item style="--n-width: 70px; margin-left: 10px;">
                  <n-button
                          type="primary"
                          @click="searchByCondition()"
                  >筛选
                  </n-button>
              </n-form-item>
              <n-form-item style="margin-left: 12px">
                  <n-button
                          type="primary"
                          @click="showForm = true"
                  >
                      添加产品
                  </n-button>
              </n-form-item>
              <n-form-item style="margin-left: 10px">
                  <n-button
                          type="error"
                          @click="deleteSelectProduct"
                  >
                      批量删除
                  </n-button>
              </n-form-item>
                      <n-form-item style="margin-left: 10px">
                        <n-button type="primary"
                                  @click="exportListInfo">导出</n-button>
                      </n-form-item>
            </div>
          </div>
        </n-form>
      </div>
      <AddProductForm :option="option" :show="showForm"  @update-page="searchByCondition" :onClose="handleClose"/>
      <UpdateProductForm
          @update-page="searchByCondition"
          :show1="showForm1"
          :onClose="handleClose2"
          :product="currentProduct"
      />
      <n-data-table
          remote
          :single-line="false"
          ref="table"
          :columns="columns"
          :data="productList"
          :loading="loading"
          :pagination="paginationReactive"
          :row-key="rowKey"
          :scroll-x="900"
          style="--n-td-padding: 2px 5px;margin-top: -5px"
          @update:checked-row-keys="handleCheck"
      />
    </CommonPage>
  </n-scrollbar>
</template>

<script setup>
import {h, onMounted, reactive, ref} from 'vue'
import api from '@/api/admin';
import ProductActions from './components/product-actions.vue';
import {useUserStore} from '@/store';
import {useRouter} from 'vue-router';
import {formatDate} from "@/utils";
import AddProductForm from './components/product-add.vue';
import UpdateProductForm from './components/product-edit.vue';
import {NImage, NTag} from "naive-ui";

const showForm = ref(false);
const showForm1=ref(false);
const searchCondition = ref({
  name: '',
  brandName: '',
	categoryId: null,
});
const handleClose = () => {
  showForm.value = false;
};
const handleClose2 = () => {
  showForm1.value = false;
};
const userStore = useUserStore()
const id=userStore.getId()
const router = useRouter()
const loading = ref(false)
const productList = ref([])
const range = ref(null)
const option = ref([
  {
    label:'全部',
    value:-1
  }
])
const brands=ref([
  {
    label:'全部',
    value:'',
  }
])
const queryBrandList = async () => {
  loading.value = true
  try {
    const res = await api.findAllProductBrand()
    if(res.code === 200) {
      res.data.map((item)=>{
        brands.value.push({
          label: item.name,
          value: item.name,
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取品牌信息失败！")
  }finally{
    loading.value = false
  }
}
const checkedRowKeysRef = ref([]);
const handleCheck =(rowKeys)=>{
    checkedRowKeysRef.value = rowKeys;
}
const columns = [
  {
    type: 'selection',
    fixed: 'left',
  },
  {
    key: 'colId',
    title: '序号',
    width: 40,
  },
  {
    key: 'id',
    title: '产品编号',
    width: 65,
  },
  {
    key: 'name',
    title: '产品名称',
    width: 200,
	  render(row) {
		  return h(
			  'a',
			  {
				  onClick: () => navigateToProductDetail(row),
				  style: {
					  color: '#358BFF',
					  cursor: 'pointer',
				  },
			  },
			  row.name
		  )
	  },
  },
  {
    key: 'categoryName',
    title: '产品分类',
    width: 85,
  },
  {
    key: 'attribute_id',
    title: '产品属性',
    width: 100,
    render(row) {
      return row.attributeDescription;
    }
  },
  {
    key: 'brandName',
    title: '产品品牌',
    width: 100,
  },
	{
		key: 'picture',
		title: '产品主图',
		width: 100, // 宽度调整为 50
		render(row) {
			// 检查是否有图片数据
			if (row.picture === null || row.picture === "" || !row.picture.trim()) {
				return h('div', {}, '尚无');
			}
			const pictures = row.picture.split(',');
			const firstPictureUrl = pictures[0].trim();
			return h(NImage, {
				src: `/api/common/download?name=${firstPictureUrl}`,
				width: 40,
				height: 40
			});
		},
	},
  {
    key: 'cost',
    title: '成本价',
    width: 70,
  },
	{
		key: 'status',
		title: '产品状态',
		width:70,
		render(row) {
			if(row.status === "在售") {
				return h(
					NTag,
					{
						type: 'success',
						bordered: false
					},
					{
						default: () => row.status
					}
				);
			}
			else if(row.status === "下架") {
				return  h(
					NTag,
					{
						type: 'error',
						bordered: false
					},
					{
						default: () => row.status
					}
				);
			}
			else if(row.status === "开发中") {
				return  h(
					NTag,
					{
						type: 'info',
						bordered: false
					},
					{
						default: () => row.status
					}
				);
			}
		}
	},
  {
    key: 'supplierName',
    title: '供应商名称',
    width: 80,
  },
	{
		key: 'operation',
		title: '操作',
		width: 120,
		render(row) {
			return h(
				ProductActions,
				{
					onClickDelete: () => onDeleteProduct(row),
					onClickEdit: () => onEditProduct(row),
				}
			);
		}
	},
]
let total = 0
const paginationReactive = reactive({
    page: 1,
    pageSize: 50,
    showSizePicker: true,
    pageSizes: [50, 100, 150],
    itemCount:0,
    prefix: () => {
        return '查询出 ' + total + '条记录';
    },
    onChange: (page) => {
        paginationReactive.page = page;
        queryByPage()
    },
    onUpdatePageSize: (pageSize) => {
        paginationReactive.pageSize = pageSize;
        paginationReactive.page = 1;
        queryByPage()
    }
});
const onDeleteProduct = async (product) => {
	$dialog.confirm({
		title: '警告',
		content: '您确定删除当前产品分类？',
		positiveText: '确定',
		negativeText: '取消',
		onPositiveClick: async () => {
			const {id} = product
			loading.value = true
			try {
				const res = await api.deleteProduct({id})
				if(res.code === 200) {
					$message.success("删除产品分类成功！")
					await searchByCondition()
				}
				else {
					$message.error(res.message)
				}
			} catch (err) {
				$message.error("删除产品分类失败！")
			}finally{
				loading.value = false
			}
		}
	})
}
const deleteSelectProduct = () => {
	if(checkedRowKeysRef.value.length <= 0) {
		$message.error("当前并未选择产品！")
		return
	}
	$dialog.confirm({
		title: '警告',
		content: '您确定删除当前所选产品？',
		positiveText: '确定',
		negativeText: '取消',
		onPositiveClick: async () => {
			const ids = checkedRowKeysRef.value.join(",")
			loading.value = true
			try {
				const res = await api.deleteProducts({params:{ids}})
				if(res.code === 200) {
					$message.success("删除所选产品成功！")
					await searchByCondition()
				}
				else {
					$message.error(res.message)
				}
			} catch (err) {
				$message.error("删除所选产品失败！")
			}finally{
				loading.value = false
			}
		},
	})
}
const searchByCondition = async ()=>{
    loading.value = true
    try {
        paginationReactive.page = 1;
        const res = await api.findPageProduct({
          params: {
	          name: searchCondition.value.name,
	          brandName: searchCondition.value.brandName,
            categoryId: searchCondition.value.categoryId,
	          pageNum:paginationReactive.page,
	          pageSize:paginationReactive.pageSize,
          }
        })
        if(res.code === 200) {
	        total = res.data.total
	        paginationReactive.itemCount = total
	        const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
	        productList.value = res.data.records.map((item,i)=>{
		        return {...item,
			        colId: baseCount + i + 1,
		        }
	        })
        }
        else {
            $message.error(res.message)
        }
    } catch (err) {
        $message.error("查询产品失败！")
    }finally{
        loading.value = false
    }
}
const currentProduct=ref(null);
const onEditProduct = async (product)=>{
  currentProduct.value = product; // 设置当前编辑的产品
  showForm1.value = true;// 显示编辑窗口
  const {id}=product
}
const queryAllProductCategory = async  () => {
	try {
		const res = await api.findAllProductCategory()
		if(res.code === 200) {
			// 调用函数生成n-cascader的options
			convertToCascaderOptions(res.data);
		}
		else {
			$message.error(res.message)
		}
	} catch (err) {
		$message.error("获取产品失败！")
	}finally{
		loading.value = false
	}
}
const exportListInfo = async () => {
  const res = await api.exportProductList({
    name: searchCondition.value.name,
    categoryId:searchCondition.value.categoryId,
    brandName: searchCondition.value.brandName
  });
  const contentDisposition = res.headers["content-disposition"]
  let original_fileName = ""
  if(contentDisposition) {
    const uri = res.headers["content-disposition"].split("=")[1]
    original_fileName = window.decodeURI(uri)
  }
  const blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
  if(window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, original_fileName);
  } else{
    const fileName = original_fileName;
    const elink = document.createElement('a')
    document.body.appendChild(elink)
    elink.download= fileName;
    elink.style.display ="none"
    elink.href  = window.URL.createObjectURL(blob)
    elink.click()
    window.URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }
}
const convertToCascaderOptions = (flatData) => {
	const idNodeMap = {}; // 用于映射id到对应的节点对象
	const opt = []; // 最终生成的级联选择器数据
	// 首先，将所有的数据节点放到一个映射表中，方便后续通过ID快速查找
	flatData.forEach(node => {
		idNodeMap[node.id] = { ...node, children: [] };
	});
	// 构建树形结构
	Object.values(idNodeMap).forEach(node => {
		if (node.parentCategoryId === null) {
			// 如果parentId为null，则该节点是根节点
			opt.push(node);
		} else {
			// 否则，将该节点添加到其父节点的children数组中
			const parentNode = idNodeMap[node.parentCategoryId];
			if (parentNode) {
				parentNode.children.push(node);
			}
		}
	});
	// 遍历并转换所有根节点
	option.value = opt.map(node=>{
		return traverse(node)
	});
}
// 转换数据结构为n-cascader所接受的格式（将name和parentName转换为label，并移除不必要的字段）
const traverse = (node) => {
	const { id, name, children } = node;
	// 如果children数组为空，则不返回children字段
	const processedNode = {
		value: id.toString(),
		label: name,
		...(children.length > 0 ? { children: children.map(child => traverse(child)) } : {})
	};
	return processedNode;
};
// 使用optionsForNCascader作为n-cascader的options
const queryByPage = async ()=>{
    loading.value = true
    try {
        const res = await api.findPageProduct(
            {
              params: {
	              pageNum:paginationReactive.page,
	              pageSize:paginationReactive.pageSize,
              }
            })
        if(res.code === 200) {
            total = res.data.total
            paginationReactive.itemCount = total
            productList.value = res.data.records.map((item,i)=>{
                return {...item,
                    colId: i+1
                }
            })
            $message.success("获取产品成功！")
        }
        else {
            $message.error(res.message)
        }
    } catch (err) {
        $message.error("获取产品失败！")
    }finally{
        loading.value = false
    }
}
const rowKey = (rowData) => {
  return rowData.id
}
const navigateToProductDetail = (row) => {
	localStorage.setItem('product', JSON.stringify(row))
	router.push({
		path: '/admin/category/product-detail',
	})
}

onMounted(()=>{
	queryAllProductCategory()
  queryBrandList()
  queryByPage()
})
</script>
<style scoped>
:deep(.n-data-table-th__title),
:deep(.n-data-table-td) {
    text-align: center;

}
:deep(.n-select) {
    width: 140px !important;
}

:deep(.two-line-description) {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2; /* 控制显示的行数 */
  overflow: hidden;
}

</style>
